package com.iss.ljx.mybatis.flexigrid;

import com.iss.ljx.mybatis.anno.Columns;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * description TODO
 *
 * @author 流星
 * @date 2022/5/11 17:29
 */
public class PadingRstType<T> {
    private Logger log =
            LogManager.getLogger(PadingRstType.class);

    private Integer total;

    private Integer page;

    private List<PageRowsType> rows =
            new ArrayList<PageRowsType>();

    private List<Object> columns =
            new ArrayList<>();

    private List<T> rawRecords;

    public Integer getTotal() {
        return total;
    }

    public void setTotal(
            Integer total) {
        this.total = total;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(
            Integer page) {
        this.page = page;
    }

    public List<PageRowsType> getRows() {
        return rows;
    }

    public void setRows(
            List<PageRowsType> rows) {
        this.rows = rows;
    }

    public List<Object> getColumns() {
        return columns;
    }

    public void setColumns(
            List<Object> columns) {
        this.columns = columns;
    }

    public List<T> getRawRecords() {
        return rawRecords;
    }

    public void setRawRecords(
            List<T> rawRecords) {
        this.rawRecords =
                rawRecords;
    }

    public void putItems() {
        if (rawRecords == null || rawRecords.size() == 0) {
            return;
        }
        Class<T> aClass = (Class<T>) rawRecords.get(0).getClass();

        Field[] fields =
                aClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Columns.class)) {
                columns.add(field.getName());
            }
        }
        PageRowsType pageRowsType;
        int index = 0;
        for (T item : rawRecords) {
            pageRowsType =
                    new PageRowsType();
            pageRowsType.setId(index);
            index++;
            rows.add(pageRowsType);
            for (Field field : fields) {
                if (field.isAnnotationPresent(Columns.class)) {
                    field.setAccessible(true);
                    try {
                        pageRowsType.addCell(field.get(item));
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
